package com.heng.test.CG;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

// 目标类
class TargetClass {
    public void doSomething() {
        System.out.println("TargetClass: Doing something.");
    }
}

// 实现MethodInterceptor接口
class CglibInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("Before method call.");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("After method call.");
        return result;
    }
}

// 测试类
public class CglibProxyExample {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(TargetClass.class);
        enhancer.setCallback(new CglibInterceptor());
        TargetClass proxy = (TargetClass) enhancer.create();
        TargetClass target = new TargetClass();
        System.out.println("TargetClass hashCode: " + target.hashCode());
        System.out.println("Proxy hashCode: " + proxy.hashCode());
    }
}